# coding:utf-8
# 报名管理
from AnalysisService.util.DATimeUtil import DateFormatUtil
from AnalysisService.util.DAMathUtil import UuidUtil
from AnalysisService.MongoUtil import MongoDB

from AnalysisService.MMKeyUtil import AVISONY_DB_NAEM, AVISONY_ENTRY_COLLECTION
from AnalysisService.util.Log import log


class EntryDB:

    def __init__(self):
        self.mongo = MongoDB(AVISONY_DB_NAEM, AVISONY_ENTRY_COLLECTION)

    def query(self, filter):
        array = self.mongo.find(filter)
        return array

    def queryByTime(self, filter):
        sort = [('createtime', -1)]
        array = self.mongo.findAndSort(filter, sort)
        return array

    def query_one(self, filter):
        one = self.mongo.find_one(filter)
        return one

    def isExist(self, phonenumber, url):

        today = DateFormatUtil.formatToToday()
        search = {"phonenumber": phonenumber, "url": url,'createtime': {'$regex': today}}
        model = self.query_one(search)

        if model is None:
            return False

        return True

    def add_one(self, name, phonenumber, source, url, remark1, remark2):

        log.i("当前时间：",DateFormatUtil.format())
        one = {
            "euid": UuidUtil.toStr(),
            "name": name,
            "phonenumber": phonenumber,
            "source": source,
            "url": url,
            "remark1": remark1,
            "remark2": remark2,
            "createtime": DateFormatUtil.format()
        }

        try:
            self.mongo.insert(one)
            return True
        except Exception as e:
            log.e('添加报名信息 - 失败 : {}'.format(phonenumber), str(e))
            return False
